package com.myblog.myblog.myException;

import com.myblog.myblog.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author gyl
 * @data 2020/5/3 17:12
 */
@RestControllerAdvice
@Slf4j
public class GenericExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(MyException.class)
    public ResultData handleRRException(MyException e){
        if (e instanceof MyException) {
            MyException e1 = (MyException) e;
            log.error(e1.getCode()+"");
            return ResultData.fail(e1.getCode(), e1.getMessage());
        }
        log.error(e.getCause().getMessage());
        log.error(e.getMessage());

        return ResultData.fail(e.getMessage());

    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultData handlerNoFoundException(java.lang.Exception e) {
        log.error(e.getMessage(), e);
        return ResultData.fail(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResultData handleDuplicateKeyException(DuplicateKeyException e){
        log.error(e.getMessage(), e);
        return ResultData.fail(99,"数据库中已存在该记录");
    }



    @ExceptionHandler(java.lang.Exception.class)
    public ResultData handleException(java.lang.Exception e){
        log.error(e.getMessage(), e);
        return ResultData.fail(e.getMessage());
    }

}